import React, { useCallback, useEffect, useState, useRef } from "react";

import { SearchCheckboxTable } from "@/views/components/SearchTable/index";
import { useTableConfig } from "@/views/components/SearchTable/hooks/useTableConfig";

import ActionsDialog from "./components/Actions/Dialog";
import LeftBtns from "./components/Actions/LeftBtns";
import RightBtns from "./components/Actions/RightBtns";

import useColumns from "./columns";
import useCommand from "./useCommand";

import { tableRequestMock1 } from "@/views/utils/mock";
import { queryPageSkuList, queryPageSpuList } from "./service";

import { useSearchParams, useLocation } from "react-router-dom";
import { Button, Space } from "antd";
import IconFont from "@/components/IconFont";
import { getCreatedSysGoods } from "./service";
import { isEmpty } from "lodash";

let isNoticeOpen = false; // 提示弹窗是否打开
let isAsyncCreateGoodsSuccess = false; // 异步生成商品是否成功
let asyncGoodsData = {}; // 异步商品数据

const ShopGoodsPage = () => {
	const ComponentName = "测试页面";
	// console.warn(`${ComponentName},重新渲染`);
	// useEffect(() => {
	// 	console.warn(`${ComponentName},初始化`);
	// }, []);
	const [failGoods, setFailGoods] = useState([]);
	const [temp1, setIsNoticeOpen] = useState(); // 更新提示弹窗状态
	const [temp2, setIsAsyncCreateGoodsSuccess] = useState(); // 更新异步生成商品状态

	const fn = useRef(null);

	const { handleCommand, visibleDialogName, customDialogProps, clearDialog } = useCommand(fn);

	const { isSkuType, tabValue, setTabValue, columns, setColumns } = useColumns({ handleCommand });
	// const tableRequest = tableRequestMock1;
	const tableRequest = isSkuType ? queryPageSkuList : queryPageSpuList;
	const tableKey = isSkuType ? "SKUGoodsManageShopTable" : "SPUGoodsManageShopTable";
	const {
		selectedKeys,
		selectedRows,
		fetchList,
		dataSource,
		form,
		query,
		pagination,
		updateDataSource,
		updateSearchQuery,
		updatePaginationParams,
		searchSimpleTableProps
	} = useTableConfig({
		tableKey,
		rowKey: "id",
		// ///
		columns,
		tableRequest,
		autoFetch: false,
		hasPagination: true,
		pageSize: 50,
		hasQuickSearch: true,
		beforeQuerySearch: false,
		resetSourceData: false,
		hasColsSetting: true,
		hasToggleSearchForm: true,
		columnResize: true,
		hasQueryLocation: "/views/goods/shop"
	});

	useEffect(() => {
		fn.current = customQuery => {
			console.log("customQuery", customQuery);
			if (customQuery) {
				if (customQuery.isSkuType) {
					setTabValue(customQuery.isSkuType ? "sku" : "spu");
					delete customQuery.isSkuType;
				}
				setTimeout(() => {
					form.setFieldsValue(customQuery);
					console.log("searchQuery", customQuery);
					updateSearchQuery(customQuery);
					fetchList(customQuery);
				}, 100);
			} else {
				fetchList(query);
			}
		};
	}, [query, isSkuType]);
	useEffect(() => {
		fetchList({ ...query, skuId: failGoods.join(',') || query.skuId });
	}, [isSkuType, failGoods]);
	const btnsProps = {
		query,
		selectedRows,
		handleCommand,
		isSkuType,
		fetchList,
		updateSearchQuery,
		dataSource
	};

	const handleNoticeOpen = () => {
		setIsNoticeOpen(true)
		isNoticeOpen = true;
	}

	const handleNoticeClose = () => {
		setIsNoticeOpen(false);
		setIsAsyncCreateGoodsSuccess(false);
		isNoticeOpen = false;
		isAsyncCreateGoodsSuccess = false;
	}

	// 轮询异步生成系统商品
	const asyncGetCreatedGoodsPoll = (taskId) => {
		handleNoticeOpen();
		let timer = setInterval(() => {
			getCreatedSysGoods({ taskId }).then(res => {
				if (res.success && !isEmpty(res.data)) {
					asyncGoodsData = res.data;
					clearInterval(timer);
					timer = null;
					if (!isNoticeOpen) {
						return;
					}
					setIsAsyncCreateGoodsSuccess(true);
					isAsyncCreateGoodsSuccess = true;
				}
			});
		}, 5000);
	}

	// 查看失败商品
	const handleCheckFailGoods = (data = []) => {
		clearDialog();
		setTabValue('sku');
		setFailGoods(data);
		form.setFieldsValue({ skuId: data.join(',') })
	}

	const actionsDialogProps = {
		visibleDialogName,
		isSkuType,
		selectedRows,
		customDialogProps,
		handleCommand,
		onCancel: clearDialog,
		asyncGetCreatedGoodsPoll,
		handleCheckFailGoods,
	};

	// 带上query参数的自动请求
	const [searchParams] = useSearchParams();
	const location = useLocation();
	useEffect(() => {
		const skuCode = searchParams.get("skuCode") || "";
		if (location.pathname == "/views/goods/shop") {
			const searchQuery = skuCode ? { skuCode } : {};
			form.setFieldsValue(searchQuery);
			// console.log("searchQuery", searchQuery);
			updateSearchQuery(searchQuery);
			fetchList(searchQuery);
		}
	}, []);

	return (
		<>
			<SearchCheckboxTable
				key={tableKey}
				leftBtns={<LeftBtns {...btnsProps} />}
				rightBtnsContent={RightBtns}
				rightBtnsContentProps={btnsProps}
				mounted={false}
				{...searchSimpleTableProps}
			/>
			<ActionsDialog {...actionsDialogProps} />
			{isNoticeOpen && (
				<div
					className="custom-notcie"
					style={{
						width: 360,
						height: 116,
						position: "fixed",
						right: 24,
						bottom: 24,
						zIndex: 900,
						padding: "16px 24px",
						overflow: "hidden",
						backgroundColor: "#fff",
						borderRadius: 4,
						boxShadow: "0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05)",
						display: "flex",
						flexDirection: "column",
						justifyContent: 'space-between'
					}}
				>
					<div style={{ display: "flex", gap: 8 }}>
						<IconFont type={isAsyncCreateGoodsSuccess ? 'iconchenggong' : 'iconjingshi'} style={{ fontSize: 20 }} />
						<span>{isAsyncCreateGoodsSuccess ? '手动生成系统商品完成' : '手动生成系统商品中，请耐心等待稍后查看结果...（关闭该窗口不影响当前任务处理）'}</span>
					</div>
					<Space style={{ display: "flex", justifyContent: "end" }}>
						<Button onClick={handleNoticeClose}>关闭{!isAsyncCreateGoodsSuccess && '不查看结果'}</Button>
						{isAsyncCreateGoodsSuccess && <Button type="primary" onClick={() => {handleCommand("生成系统商品结果", asyncGoodsData); handleNoticeClose()}}>查看结果</Button>}
					</Space>
				</div>
			)}
		</>
	);
};
export default React.memo(ShopGoodsPage, () => {
	return true;
});
